<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <el-dialog v-model="dialogVisible" title="客户信息" :width="600">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="customer-form"
    >
      <!-- 基础信息 -->
      <el-form-item label="客户名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入客户名称" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="客户类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择客户类型">
          <el-option label="个人客户" value="individual" />
          <el-option label="企业客户" value="enterprise" />
        </el-select>
      </el-form-item>

      <el-form-item label="联系地址" prop="address">
        <el-input
          v-model="formData.address"
          placeholder="请输入联系地址"
          type="textarea"
          :rows="3"
          max-length="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="客户状态" prop="status">
        <el-switch
          v-model="formData.status"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { reactive, ref, watch } from 'vue';

// 表单属性
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  },
  visible: {  // 接收父组件的显示状态
    type: Boolean,
    default: false
  }
});

// 表单事件
const emit = defineEmits(['update:visible', 'save']);

//本地状态管理，避免直接修改props
const dialogVisible = ref(props.visible);

// 监听props的visible变化，同步到本地状态
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  }
);

// 监听本地状态变化，通知父组件更新
watch(
  () => dialogVisible.value,
  (newVal) => {
    emit('update:visible', newVal);
  }
);

// 表单引用
const formRef = ref(null);

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  phone: '',
  type: '',
  address: '',
  status: true
});

// 重置表单
const resetForm = () => {
  formData.id = '';
  formData.name = '';
  formData.phone = '';
  formData.type = '';
  formData.address = '';
  formData.status = true;

  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

// 判断是否为编辑状态
const isEdit = ref(!!props.modelValue.id);

// 监听编辑数据变化
watch(
  () => props.modelValue,
  (val) => {
    if (val && val.id) {
      isEdit.value = true;
      // 复制并转换数据到表单
      formData.id = val.id;
      formData.name = val.customerName || val.name;
      formData.phone = val.phone;
      formData.email = val.email;
      formData.address = val.address;
      formData.remark = val.remark;
      // 修复客户类型转换（0->个人，1->企业）
      formData.type = val.type === '0' ? 'individual' : 'enterprise';
      // 修复客户状态转换（1->启用，0->禁用）
      formData.status = val.status === 1;
    } else {
      isEdit.value = false;
      resetForm();
    }
  },
  { immediate: true }
);

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 2, max: 50, message: '客户名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  type: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入联系地址', trigger: 'blur' }
  ]
});

// 取消按钮
const handleCancel = () => {
  dialogVisible.value = false;
  resetForm();
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    emit('save', { ...formData });
    ElMessage.success(isEdit.value ? '客户信息更新成功' : '客户添加成功');
    dialogVisible.value = false;
    resetForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};
</script>

<style scoped>
.customer-form {
  margin-top: 15px;
}

::v-deep .el-form-item {
  margin-bottom: 15px;
}
</style>
